<?php
declare (strict_types=1);

namespace app\advertiser\service;

use aliyun\AliyunOss;
use app\admin\model\advertiser\AdvertiserMatter;
use app\admin\model\advertiser\AdvertiserTask;
use app\advertiser\validates\AdvertiserMatterValidate;
use app\BaseService;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 推广物服务层
 */
class AdMatterService extends BaseService
{

    /**
     * 推广物列表
     * @param array $params
     * @param int $type
     * @return Json
     */
    public function list(array $params, int $type): Json
    {
        if(defined("WS_AD_USER_ID")){
            $where[] = ['ad_user_id', '=', WS_AD_USER_ID];
        }
        $where[] = ['type', '=', $type];
        $where[] = ['closed', '=', 0];
        //搜索名称
        if ($params['name']) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        //创建时间筛选
        if ($params['start_time'] && $params['end_time']) {
            $start_time = (int)$params['start_time'];
            $end_time = (int)$params['end_time'];
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        //获取列表
        $data = AdvertiserMatter::getList($where, $params['page'], $params['limit'], 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 推广物全部列表
     * @param array $params
     * @param int $type
     * @return Json
     */
    public function listAll(array $params, int $type): Json
    {
        $where[] = ['ad_user_id', '=', WS_AD_USER_ID];
        $where[] = ['type', '=', $type];
        $where[] = ['closed', '=', 0];
        //搜索名称
        if ($params['name']) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        //获取列表
        $data = AdvertiserMatter::getListAll($where, 'id desc');
        return jsonReturn(1, $data);
    }

    /**
     * 推广物增加
     * @param array $params
     * @param int $type
     * @return Json
     */
    public function add(array $params, int $type): Json
    {
        //验证数据
        try {
            validate(AdvertiserMatterValidate::class)->scene('add')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //判断是否重复
        $where = ['appid' => $params['appid'], 'ad_user_id' => WS_AD_USER_ID, 'type' => $type];
        $Matter = AdvertiserMatter::findOne($where);
        if ($Matter) {
            return jsonReturn(0, [], '当前APPID已存在');
        }
        //处理参数
        $params['ad_user_id'] = WS_AD_USER_ID;
        $params['type'] = $type;
        $params['auth_info'] = json_encode([]);
        $params['create_time'] = time();
        $params['update_time'] = time();
        //写入管理员
        $id = AdvertiserMatter::insertGetId($params);
        if ($id) {
            return jsonReturn(1, [], '添加成功');
        }
        return jsonReturn(0, [], '添加失败');
    }

    /**
     * 推广物编辑
     * @param array $params
     * @param int $type
     * @return Json
     */
    public function edit(array $params, int $type): Json
    {
        $user_id = WS_AD_USER_ID;
        //验证数据
        try {
            validate(AdvertiserMatterValidate::class)->scene('edit')->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return jsonReturn(0, [], $e->getError());
        }
        //查询当前id是否存在
        $where[] = ['id', '=', $params['id']];
        $where[] = ['type', '=', $type];
        $where[] = ['ad_user_id', '=', $user_id];
        $where[] = ['closed', '=', 0];
        $Model = AdvertiserMatter::where($where)->find();
        if (!$Model) {
            return jsonReturn(0, [], '推广物不存在');
        }
        //记录原来的头像和二维码
        $old_avatar = $Model->avatar;
        $old_qrcode = $Model->qrcode;
        //判断是否存在审核通过或者已发布的推广任务
        $where2[] = ['matter_id', '=', $params['id']];
        $where2[] = ['ad_user_id', '=', $user_id];
        $where2[] = ['status', 'in', [4, 5, 6]];
        $where2[] = ['closed', '=', 0];
        $res = AdvertiserTask::findOne($where2, 'id');
        if ($res) {
            return jsonReturn(0, [], '存在审核通过或者已发布的推广任务');
        }
        //修改时间
        $params['update_time'] = time();
        //编辑
        $res = $Model->save($params);
        if ($res) {
            $AliyunOss = new AliyunOss();
            //删除原来的头像
            if ($params['avatar'] != $old_avatar) {
                $AliyunOss->deleteObject($old_avatar);
            }
            //删除原来的二维码
            if ($params['qrcode'] != $old_qrcode) {
                $AliyunOss->deleteObject($old_qrcode);
            }
            //更改推广任务为待审核
            $where3[] = ['matter_id', '=', $params['id']];
            $where3[] = ['ad_user_id', '=', $user_id];
            $where3[] = ['status', 'in', [4, 5, 6]];
            $where3[] = ['closed', '=', 0];
            AdvertiserTask::update(['status' => 2], $where3);
            return jsonReturn(1, [], '编辑成功');
        }
        return jsonReturn(0, [], '编辑失败');
    }

    /**
     * 推广物删除
     * @param int $id
     * @param int $type
     * @return Json
     */
    public function del(int $id, int $type): Json
    {
        //查询当前id是否存在
        $where[] = ['id', '=', $id];
        $where[] = ['ad_user_id', '=', WS_AD_USER_ID];
        $where[] = ['type', '=', $type];
        $where[] = ['closed', '=', 0];
        $res = AdvertiserMatter::findOne($where);
        if (!$res) {
            return jsonReturn(0, [], '不存在');
        }
        //判断是否存在推广任务
        $res1 = AdvertiserTask::findOne(['matter_id' => $id, 'closed' => 0]);
        if ($res1) {
            return jsonReturn(0, [], '存在推广任务,不能删除');
        }
        //删除
        $res2 = AdvertiserMatter::deleteData(['id' => $id]);
        if ($res2) {
            $AliyunOss = new AliyunOss();
            //删除原来的头像和二维码
            $AliyunOss->deleteObject($res['avatar']);
            $AliyunOss->deleteObject($res['qrcode']);
            return jsonReturn(1, [], '删除成功');
        }
        return jsonReturn(0, [], '删除失败');
    }

}
